import { ref, onMounted, computed } from "vue";

type Theme = "light" | "dark";

const THEME_KEY = "app-theme";
const THEME_ATTRIBUTE = "data-theme";

/**
 * 主题切换 Composable
 */
export const useTheme = () => {
    const theme = ref<Theme>("light");

    /**
     * 获取当前主题
     */
    const getTheme = (): Theme => {
        if (typeof window === "undefined") return "light";

        // 优先从 localStorage 读取
        const savedTheme = localStorage.getItem(THEME_KEY) as Theme;
        if (savedTheme === "dark" || savedTheme === "light") {
            return savedTheme;
        }

        // 检查系统偏好
        if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
            return "dark";
        }

        return "light";
    };

    /**
     * 设置主题
     */
    const setTheme = (newTheme: Theme): void => {
        if (typeof window === "undefined") return;

        const root = document.documentElement;

        if (newTheme === "dark") {
            root.setAttribute(THEME_ATTRIBUTE, "dark");
        } else {
            root.removeAttribute(THEME_ATTRIBUTE);
        }

        // 保存到 localStorage
        localStorage.setItem(THEME_KEY, newTheme);
        theme.value = newTheme;
    };

    /**
     * 切换主题
     */
    const toggleTheme = (): void => {
        const newTheme: Theme = theme.value === "dark" ? "light" : "dark";
        setTheme(newTheme);
    };

    // 初始化主题
    onMounted(() => {
        const currentTheme = getTheme();
        setTheme(currentTheme);
    });

    // 计算属性：是否为暗黑模式
    const isDark = computed(() => theme.value === "dark");

    return {
        theme,
        isDark,
        toggleTheme,
        setTheme,
    };
};
